package sys

import (
	"errors"
	"gitee.com/freelifer/module-admin/model"
	"gitee.com/freelifer/module-web-base/request"
	"github.com/go-spring/spring-core/gs"
	"gorm.io/gorm"
)

func init() {
	// SpringBoot.RegisterBean(new(Service)).AsInterface((*types.FileProvider)(nil))
	gs.Object(new(RoleService)).Init(func(c *RoleService) {
	})
}

type RoleService struct {
	DB *gorm.DB `autowire:""`
}

func (s *RoleService) CreateRole(role model.SysRole) (err error, r model.SysRole) {
	var roleBox model.SysRole
	if !errors.Is(s.DB.Where("role_id = ?", role.RoleId).First(&roleBox).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同角色id"), role
	}
	err = s.DB.Create(&role).Error
	return err, role
}

func (s *RoleService) GetRoleInfoList(info request.PageInfo) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := s.DB.Model(&model.SysRole{})
	err = db.Where("parent_id = ?", "0").Count(&total).Error
	var roles []model.SysRole
	err = db.Limit(limit).Offset(offset).Preload("DataAuthorityId").Where("parent_id = ?", "0").Find(&roles).Error
	if len(roles) > 0 {
		for k := range roles {
			err = s.findChildrenAuthority(&roles[k])
		}
	}
	return err, roles, total
}

func (s *RoleService) GetRoleInfo(role model.SysRole) (err error, r model.SysRole) {
	err = s.DB.Preload("DataAuthorityId").Where("role_id = ?", role.RoleId).First(&r).Error
	return err, r
}

func (s *RoleService) UpdateAuthority(role model.SysRole) (err error, r model.SysRole) {
	err = s.DB.Where("role_id = ?", role.RoleId).First(&model.SysRole{}).Updates(&role).Error
	return err, role
}

//func (s *RoleService) DeleteAuthority(role model.SysRole) (err error) {
//	if !errors.Is(s.DB.Where("role_id = ?", role.RoleId).First(&model.SysUser{}).Error, gorm.ErrRecordNotFound) {
//		return errors.New("此角色有用户正在使用禁止删除")
//	}
//	if !errors.Is(s.DB.Where("parent_id = ?", role.RoleId).First(&model.SysRole{}).Error, gorm.ErrRecordNotFound) {
//		return errors.New("此角色存在子角色不允许删除")
//	}
//	db := s.DB.Preload("SysBaseMenus").Where("authority_id = ?", role.RoleId).First(role)
//	err = db.Unscoped().Delete(role).Error
//	if err != nil {
//		return
//	}
//	if len(role.SysBaseMenus) > 0 {
//		err = s.DB.Model(role).Association("SysBaseMenus").Delete(role.SysBaseMenus)
//		if err != nil {
//			return
//		}
//		// err = db.Association("SysBaseMenus").Delete(&auth)
//	} else {
//		err = db.Error
//		if err != nil {
//			return
//		}
//	}
//	err = s.DB.Delete(&[]system.SysUseAuthority{}, "sys_authority_authority_id = ?", role.RoleId).Error
//	CasbinServiceApp.ClearCasbin(0, role.RoleId)
//	return err
//}

func (s *RoleService) findChildrenAuthority(role *model.SysRole) (err error) {
	err = s.DB.Preload("DataAuthorityId").Where("parent_id = ?", role.RoleId).Find(&role.Children).Error
	if len(role.Children) > 0 {
		for k := range role.Children {
			err = s.findChildrenAuthority(&role.Children[k])
		}
	}
	return err
}
